
package isv

import (
    "dhfshop/models"
	"strings"
	"errors"
	"github.com/astaxie/beego/orm"
)

//授权管理
type Authorize struct {
	AuthorizeId   int64   `orm:"column(authorize_id);pk;auto" json:"authorize_id" form:"authorize_id"` 
	TypeId        int     `orm:"column(type_id);default(0)" json:"type_id" form:"type_id"`        //
	AppId         string  `orm:"column(app_id);size(32);unique" json:"app_id" form:"app_id"` 
	VerifyTicket  string  `orm:"column(verify_ticket)" json:"verify_ticket" form:"verify_ticket"`  //
	TicketTime    string  `orm:"column(ticket_time)" json:"ticket_time" form:"ticket_time"`        //收到时间
    AccessToken   string  `orm:"column(access_token)" json:"access_token" form:"access_token"`     //
	ExpiresIn     int64   `orm:"column(expires_in)" json:"expires_in"`                             //
}

func init() {
    orm.RegisterModel(new(Authorize))   
}

func AddAuthorize(m *Authorize) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetAuthorizeByAppId(appId string) (v *Authorize, err error) {
	o := models.GetDefaultDB()
	v = &Authorize{AppId: appId}
	if err = o.Read(v, "AppId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAuthorizeByTypeId(typeId int) (v *Authorize, err error) {
	o := models.GetDefaultDB()
	v = &Authorize{TypeId: typeId}
	if err = o.Read(v, "TypeId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllAuthorizes(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*Authorize, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Authorize))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Authorize
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateAuthorizeByAppId(m *Authorize, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Authorize{AppId: m.AppId}
	if err = o.Read(&v, "AppId"); err != nil {
		return err
	}else{
	    m.AuthorizeId = v.AuthorizeId
		if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteAuthorizeByAppid(appId string) (err error) {
	o := models.GetDefaultDB()
	v := Authorize{AppId: appId}
	if err = o.Read(&v, "AppId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

func SaveTicketByAppId(appId,verifyTicket,ticketTime string) (err error) {
	o := models.GetDefaultDB()
	v := Authorize{AppId:appId}
	m := Authorize{AppId:appId,VerifyTicket:verifyTicket,TicketTime:ticketTime}
	if err = o.Read(&v, "AppId"); err != nil {
		_, err = o.Insert(&m)
		return
	}
	m.AuthorizeId = v.AuthorizeId
    if _, err = o.Update(&m,"VerifyTicket","TicketTime"); err != nil {
		return
	}
	return
}

func SaveTokenByAppId(appId,token string,expiresIn int64) (err error) {
	o := models.GetDefaultDB()
	v := Authorize{AppId:appId}
	m := Authorize{AppId:appId,AccessToken:token,ExpiresIn:expiresIn}
	if err = o.Read(&v, "AppId"); err == nil {
	    m.AuthorizeId = v.AuthorizeId
		if _, err = o.Update(&m, "access_token", "expires_in"); err != nil {
		   return
		}
	}
	return nil
}

func QueryAuthByTime(refTime int64) (auths []*Authorize, err error) {
	auths = []*Authorize{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Authorize)).Filter("expires_in__lte", refTime)
	_, err = qs.All(&auths)
	return
}

